﻿@using AdvancedPoll.ViewModels;
@using AdvancedPoll.Models;

@if (Model.IsShown)
{

    Script.Require("JQuery");
    Script.Require("JQPlotPlugin");
    Script.Include("Plugins/jqplot.categoryAxisRenderer.min.js");
    Script.Include("Plugins/jqplot.barRenderer.min.js");
    Script.Include("Plugins/jqplot.canvasAxisTickRenderer.min.js");
    Script.Include("Plugins/jqplot.highlighter.min.js");
    Script.Include("jquery.tipsy.js");
    Style.Include("tipsy.css");
    Style.Require("JQPlotStyle");
    var height = String.Format("{0}px", Model.Choices.Count * 50);
    <div>
        <div id="chart" style="width: 150px; height: @height; display: none"></div>
    </div>

    if (Model.IsOpen)
    {
        Script.Require("MD5");
        Script.Require("FingerPrint");

    <span id="AdvancedPoll_Error"></span>
    <div id="PollContainer">
        <label>@Model.Question</label>

        @using (Html.BeginFormAntiForgeryPost())
        {
            foreach (PollChoiceRecord a in @Model.Choices)
            {
            <input type="checkbox" id="answer @a.Id" style="margin-bottom: 4px"/><label for="answer @a.Id" style="display: inline; margin-left: 5px">@a.Answer</label><br />
            }
            <button type="submit" id="PollSubmit">@T("Vote")</button>
        }
    </div>

        using (Script.Foot())
        {
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: '@Url.Action("CanVote", "Vote", new { area = "AdvancedPoll", id = @Model.Id })',
                traditional: true,
                data: {
                    fingerPrint: $.fingerprint(),
                    __RequestVerificationToken: '@Html.AntiForgeryTokenValueOrchard()'
                }
            }).done(function (response) {
                if (response.canVote) {
                    $('#PollSubmit').parent().submit(function (event) {
                        event.preventDefault();
                        var t = new Array();
                        $('#PollContainer').find('input:checkbox:checked').each(function () {
                            t.push($(this).attr('id').replace("answer ", ""));
                        });
                        $.ajax({
                            type: "POST",
                            url: '@Url.Action("Vote", "Vote", new { area = "AdvancedPoll", id = @Model.Id })',
                            traditional: true,
                            data: {
                                fingerPrint: $.fingerprint(),
                                votes: t,
                                __RequestVerificationToken: '@Html.AntiForgeryTokenValueOrchard()'
                            }
                        }).done(function (response) {
                            if (!response.success)
                                //alert(response.error);
                                $('#AdvancedPoll_Error').html(response.error);
                            else {
                                alert("Thanks for voting!");
                                //$('#AdvancedPoll_Error').html("Thanks for voting!");
                                //$('#PollContainer').html('');
                                //location.reload();
                                loadPollResult();
                            }
                        }).fail(function (jqXHR, textStatus) {
                            alert(textStatus);
                        });
                    });

                    $('#PollContainer').find('input:checkbox').change(function () {
                        var num = $('#PollContainer').find('input:checkbox:checked').size();
                        if (num >= '@Model.MaxVotes') {
                            $('#PollContainer').find('input:checkbox:not(:checked)').each(function () {
                                $(this).attr('disabled', 'disabled');
                            });
                        }
                        else {
                            $('#PollContainer').find('input:checkbox:not(:checked)').each(function () {
                                $(this).removeAttr('disabled');
                            });
                        }
                    });
                }
                else {
                    loadPollResult();
                }
            });
        });
    </script>
        }
    }
    else
    {
        using (Script.Foot())
        {
    <script type="text/javascript">
        $(document).ready(function () {
            loadPollResult();
        });
    </script>
        }
    }

    using (Script.Foot())
    {
    <script type="text/javascript">
        function loadPollResult() {
            $.ajax({
                type: "GET",
                url: '@Url.Action("GetResult", "Vote", new { area = "AdvancedPoll", id = @Model.Id })',
                traditional: true,
                data: {}
            }).done(function (response) {
                $('#chart').show();
                $('#PollContainer').hide();
                var line = response.result;
                $('#chart').jqplot([line], {
                    title: '@Model.Question',
                    animate: true,
                    showTooltip: true,
                    gridPadding: { right: 0, left: 0 },
                    seriesDefaults: {
                        renderer: $.jqplot.BarRenderer,
                        rendererOptions: {
                            // Set the varyBarColor option to true to use different colors for each bar.
                            // The default series colors are used.
                            varyBarColor: true,
                            barDirection: 'horizontal'
                        },
                        pointLabels: { show: true, location: 'e', edgeTolerance: -15, format: "%s" },
                        yaxis: 'y2axis'
                    },
                    axes: {
                        y2axis: {
                            renderer: $.jqplot.CategoryAxisRenderer,
                            location: 'e',
                            rendererOptions: { sortMergedLabels: true },
                            pad: 1.05,
                            tickOptions: {
                                formatString: '<span title="%s">%s</span>',
                                showGridline: false,
                                markSize: 0
                            }
                        }
                    },
                    highlighter: {
                        tooltipAxes: 'x',
                        sizeAdjust: 10,
                        show: true,
                        tooltipLocation: 'n',
                        useAxesFormatters: true
                    }
                });
                $('.tickSpan').tipsy();
            }).fail(function (jqXHR, textStatus) {
                alert("error" + textStatus);
            });
        }
    </script>
    }
}
else
{
    <p>Poll is hidden!</p>
}